import socket
import time
import threading
import datetime
import pygame
import os
from pygame.locals import QUIT, KEYDOWN, K_f, K_F11, FULLSCREEN

local_ip = "192.168.43.101"
local_port = 8000
width = 500
height = 280

# jpeg 20 fps
# esp32 spi dma temp buffer MAX Len: 4k

#import datetime
#import os
#import requests
# 创建 文件夹的时间

mkfile_time = 0                                                                                                                                      
start=0

def server():
    while True:
        conn, addr = sk.accept()
        print("hello client,ip:")
        screen.blit(draw_text("connect",[0,255,0]), (385, 50))
        pygame.display.flip()
        print(addr)
        t = threading.Thread(target=receiveThread, args=(conn,))
        t.setDaemon(True)
        t.start()

def receiveThread(conn):
    conn.settimeout(10)
    conn_end = False
    pack_size = 1024*5
    a=1
    while True:
        if conn_end:
            break
        img = b""
        tmp = b''
        while True:
            try:
                client_data = conn.recv(1)
            except socket.timeout:
                conn_end = True
                break
            if tmp == b'\xFF' and client_data == b'\xD8':
                img = b'\xFF\xD8'
                break
            tmp = client_data
        while True:
            try:
                client_data = conn.recv(4096)
            except socket.timeout:
                client_data = None
                conn_end = True
            if not client_data:
                break
            # print("received data,len:",len(client_data) )
#             if client_data:
#                 img += client_data               
            img += client_data
            if img[-2:] == b'\xFF\xD9':
                break
            if len(client_data) > pack_size:
                break
        print("recive end, pic len:", len(img))
        
        mkfile_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y_%m_%d_%H_%M_%S")
        f = open(r"C:\Users\wyc\Desktop\abnormal_people\ "+str(mkfile_time)+".jpg", "wb")
        f.write(img)
        f.close()
        
        if not img.startswith(b'\xFF\xD8') or not img.endswith(b'\xFF\xD9'):
            print("image error")
            continue
        
        '''
        fpath='D:\\' + mkfile_time  # 指定放在D 盘 目录下
        if not os.path.exists(fpath):  # 以 sku命名 的 大的 文件夹
            os.makedirs(fpath)  # makedirs 创建多级目录文件夹，mkdir创建一个文件夹
        r2 = requests.get(img)
        with open(fpath + '/' + images_name, "wb") as ff:
            ff.write(r2.content)
        '''
        
        try:
            surface = pygame.image.load(r"C:\Users\wyc\Desktop\abnormal_people\ "+str(mkfile_time)+".jpg").convert()
            screen.blit(surface, (0, 0))
            pygame.display.update()
            print("recieve ok")
        except Exception as e:
            print(e)
        a=a+1
    conn.close()
    screen.blit(draw_text("exit",[255,0,0]), (390, 50))
    pygame.display.flip()
    print("receive thread end")

def draw_text(content,background_color):
    myimage=pygame.image.load(r"C:\Users\wyc\Desktop\white.png") #把变量myimage赋给导入的图片
    screen.blit(myimage,[380,50])
    font = pygame.font.Font('C:\Windows\Fonts\simfang.ttf', 20)
    text = font.render(content, True, (0, 0, 0),background_color)
    return text
#初始化
flag=0
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = pygame.display.set_mode((width, height), 0, 32) 
pygame.display.set_caption("pic from client")


#screen=pygame.display.set_mode([640,480])  #窗口大小：640*480
screen.fill([255,255,255])#用白色填充窗口
myimage=pygame.image.load(r"C:\Users\wyc\Desktop\sbtn.jpg") #把变量myimage赋给导入的图片
myimage2=pygame.image.load(r"C:\Users\wyc\Desktop\sblack.jpg")
screen.blit(myimage,[400,150]) #在100,100的地方画出这个图片（100和100为左部和上部）
screen.blit(draw_text("连接状态:",[255,255,255]), (380, 25))
screen.blit(draw_text("unconnect",[255,0,0]), (380, 50))
pygame.display.flip()

if __name__ == '__main__':
    while True: 
        for event in pygame.event.get():#获得事件
            if event.type==pygame.MOUSEBUTTONDOWN : #判断鼠标位置以及是否摁了下去。
                 x,y=event.pos
                 if x>=400 and x<=450 and y>=150 and y<=200:
                     flag=1
                     #做需要做的事情，如开始游戏
                     while flag:
                         screen.blit(myimage2,[0,0])
                         pygame.display.flip()
                         ip_port = (local_ip, local_port)
                         sk = socket.socket()
                         sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                         sk.bind(ip_port)
                         sk.listen(50)
                         print("accept now,wait for client")


                         tmp = threading.Thread(target=server, args=())
                         tmp.setDaemon(True)
                         tmp.start()
                         
                         while True:
                             for event in pygame.event.get():#遍历所有事件
                                 if event.type == pygame.QUIT:#单击关闭窗口便退出
                                     exit()
          
   
        
        
    


